//
//  MineSettingViewController.m
//  shopping
//
//  Created by 马田成 on 2017/8/31.
//  Copyright © 2017年 qianyi. All rights reserved.
//

#import "MineSettingViewController.h"
#import "MineSettingNormalTableViewCell.h"
#import "MineNormalReuseTableViewCell.h"
#import "MineHelpViewController.h"
#import "MineSettingMessageViewController.h"
#import "MineSettingYJFKViewController.h"
#import "AboutUsViewController.h"
#import "LoginViewController.h"

@interface MineSettingViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) UILabel *cacheLabel;
@end

@implementation MineSettingViewController
- (void)viewWillAppear:(BOOL)animated{
    
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self creationView];
    [self regeditCell];
    
    // Do any additional setup after loading the view.
}
- (void)creationView{

    [self setTitle:@"设置"];
    
    UIView *viewOf = [[UIView alloc] init];
    viewOf.frame = CGRectMake(0, 0, DEF_SCREEN_WIDTH, 1);
    [self.view addSubview:viewOf];
    viewOf.backgroundColor = [UIColor colorWithRed:204 / 255.0f green:204 / 255.0f  blue:204 / 255.0f  alpha:1];
    
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.frame = CGRectMake(0, 1, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT - 64);
    
    
    self.tableView.tableFooterView = [[UITableView alloc] initWithFrame:CGRectZero];
    
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //   self.tableView.estimatedRowHeight = 400;
    self.tableView.separatorStyle = UITableViewCellAccessoryNone;//去掉分割线
    
    
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = [UIColor colorWithRed:245 / 255.0f green:245 / 255.0f blue:245 / 255.0f alpha:1];
//    UIButton *buttonOut = [[UIButton alloc] init];
//    [self.view addSubview:buttonOut];
//    [buttonOut mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self.view);
//        make.right.equalTo(self.view);
//        make.bottom.equalTo(self.view);
//        make.height.offset(45);
//        
//    }];
//    [buttonOut setTitle:@"退出登录" forState:UIControlStateNormal];
//    buttonOut.backgroundColor = [UIColor whiteColor];
//    [buttonOut setTitleColor:getColor(@"222222") forState:UIControlStateNormal];
//    [buttonOut addTarget:self action:@selector(outLick) forControlEvents:UIControlEventTouchUpInside];
//    
//    UIView *view = [[UIView alloc] init];
//    [self.view addSubview:view];
//    [view mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self.view);
//        make.right.equalTo(self.view);
//        make.bottom.equalTo(buttonOut.mas_top);
//        make.height.offset(1);
//        
//    }];
//    view.backgroundColor = getColor(@"eeeeee");
    

    
}

- (void)regeditCell{
    
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MineSettingNormalTableViewCell" bundle:nil] forCellReuseIdentifier:@"MineSettingNormalTableViewCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MineNormalReuseTableViewCell" bundle:nil] forCellReuseIdentifier:@"MineNormalReuseTableViewCell"];
    
    
    
}
#pragma mark - ---------- Section的数量 ----------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark - ---------- 每个Section的高度 ----------
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}

#pragma mark - ---------- Cell的数量 ----------
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
    
    
}

#pragma mark - ---------- 每个Cell的高度 ----------
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 50;
    
}

#pragma mark - ---------- 每个Cell的内容 ----------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 1) {
        
        MineSettingNormalTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"MineSettingNormalTableViewCell" forIndexPath:indexPath];
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.leftLabel.text = @"清理缓存";
        cell.rightImg.hidden = YES;
        
        self.cacheLabel = [[UILabel alloc] init];
        self.cacheLabel.textAlignment = NSTextAlignmentRight;
        self.cacheLabel.font = [UIFont systemFontOfSize:13];
        self.cacheLabel.text = [NSString stringWithFormat : @"%.2fM" , [self filePath]];
        [cell addSubview:self.cacheLabel];
        [self.cacheLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell).with.offset(10);
            make.right.equalTo(self.view).with.offset(-10);
            make.bottom.equalTo(cell).with.offset(-10);
            make.width.offset(100);
        }];
        return cell;
    }else if (indexPath.row == 0) {
    
        MineNormalReuseTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"MineNormalReuseTableViewCell" forIndexPath:indexPath];
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.leftLabel.text = @"消息通知";
        return cell;
        
    }
    
//    else if (indexPath.row == 2) {
//        
//        MineNormalReuseTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"MineNormalReuseTableViewCell" forIndexPath:indexPath];
//        
//        cell.selectionStyle=UITableViewCellSelectionStyleNone;
//        cell.leftLabel.text = @"帮助";
//        return cell;
//        
//    }
    
    else if (indexPath.row == 2) {
        
        MineNormalReuseTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"MineNormalReuseTableViewCell" forIndexPath:indexPath];
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.leftLabel.text = @"意见反馈";
        return cell;
        
    }else  {
        
        MineNormalReuseTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"MineNormalReuseTableViewCell" forIndexPath:indexPath];
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.leftLabel.text = @"关于我们";
        return cell;
        
    }
    
    
    
}
#pragma mark - ---------- 每个Cell的点击事件 ----------
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (indexPath.row == 2) {
//        MineHelpViewController *vc = [[MineHelpViewController alloc] init];
//        vc.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:vc animated:YES];
//        
//    }else
    
    
    if (indexPath.row == 0){
    
        MineSettingMessageViewController *vc = [[MineSettingMessageViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (indexPath.row == 2){
    
        MineSettingYJFKViewController *vc = [[MineSettingYJFKViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (indexPath.row == 3){
        
        AboutUsViewController *vc = [[AboutUsViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (indexPath.row ==1){
    
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否清除缓存" preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
            [self clearFile];
            
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
        [alert addAction:action];
        [alert addAction:cancel];
        [self showDetailViewController:alert sender:nil];
        //清除缓存

    }
    
    
    
}
//首先计算单个文件的大小

- (long long)fileSizeAtPath:(NSString *)filePath{
    
    NSFileManager * manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error : nil] fileSize];
        
    }
    
    return 0 ;
    
}

//遍历文件夹获得文件夹大小，返回多少M

- (float)folderSizeAtPath:(NSString *)folderPath{
    
    NSFileManager * manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath]) return 0 ;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator];
    
    NSString * fileName;
    
    long long folderSize = 0 ;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
        
    }
    
    return folderSize/( 1024.0 * 1024.0 );
    
}

// 显示缓存大小

- (float)filePath

{
    
    NSString * cachPath = [NSSearchPathForDirectoriesInDomains( NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    
    return [self folderSizeAtPath:cachPath];
    
}

// 清理缓存

- (void)clearFile

{
    
    NSString * cachPath = [NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    
    NSArray * files = [[NSFileManager defaultManager] subpathsAtPath :cachPath];
    
    NSLog (@"cachpath = %@" , cachPath);
    
    for (NSString *p in files) {
        
        NSError *error = nil ;
        
        NSString *path = [cachPath stringByAppendingPathComponent:p];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath :path]){
            
            [[NSFileManager defaultManager] removeItemAtPath :path error :&error];
            
        }
        
    }
    
    [self performSelectorOnMainThread:@selector(clearCachSuccess) withObject:nil waitUntilDone:YES];
    
}

- (void)clearCachSuccess

{
    
    NSLog(@"清理成功");
    
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message: @"缓存清理完毕" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    
    [alertView show];
    self.cacheLabel.text = nil;
    
    [_tableView reloadData];//清理完之后重新导入数据
    
}

- (void)outLick{

    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    
    NSString *token = [PublicFunction getConfigWithKey:@"token"];
    
    [productParams setValue:token forKey:@"token"];
    
    
    [[MNetworkHandler sharedInstance]conURL:adminLoginloginOut networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
        
        
        
        if ([[returnData objectForKey:@"code"]intValue]==1) {
            
            
            [PublicFunction removeConfigWithKey:@"token"];
            

            LoginViewController *vc = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];

        }
        
        else {
            
            
            [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
            
            
        }
        
        
    } failureBlock:^(NSError *error) {
        
        NSLog(@"%@",error);
        
//        [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
        
        
    }];

    
   
    
    

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
